import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApiService } from '../api/api.service';
import { ApiUrl } from '../api/ApiUrl';
import { UserVO } from '../vo/UserVO';
import { AnswerVO } from '../vo/Answervo';
import { ToastController } from '@ionic/angular';
import { Router } from '@angular/router';
import { ArticleVO } from '../vo/ArticleVO';
import { DomSanitizer } from '@angular/platform-browser';
import { ActionSheet, ActionSheetOptions } from '@ionic-native/action-sheet/ngx';
import { ActionSheetController , LoadingController , Platform } from '@ionic/angular';
declare var Wechat;
@Component({
  selector: 'app-article',
  templateUrl: './article.page.html',
  styleUrls: ['./article.page.scss'],
})
export class ArticlePage implements OnInit {
  articleid: any;
  userItem: UserVO;
  isCollect: boolean;
  item: AnswerVO;
  collectColor: string;
  likeColor: string;
  articleItem: ArticleVO;
  curl: any;
  actionSheetCtrl: ActionSheet;
  link = '';
  constructor(private router: Router, private sanitizer: DomSanitizer, private actionSheetController: ActionSheetController,
    public loadingCtrl: LoadingController, platform: Platform,
    private toastController: ToastController, public api: ApiService, public activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.articleid = this.activatedRoute.snapshot.paramMap.get('iid');
    // 根据ID获取curl
    console.log(this.articleid + '1111');
    this.getCurl();
    this.userItem = ApiUrl.user;
    if (this.userItem !== null) {
      // 第一次进来判断该用户是否收藏过
      this.collectOrNot();
      // 第一次进来判断该用户是否点赞过
      this.likeOrnot();
      // 第一次进来 新增浏览记录
      this.addbrowse();
    }
  }
  getCurl() {
    this.api.getItem<ArticleVO>(ApiUrl.findOneArticle,
      {'id': this.articleid}).subscribe(response => {
      if (response === null) {
        console.log('没有数据返回');
        return;
      }
      this.articleItem = response;
      this.curl = this.sanitizer.bypassSecurityTrustResourceUrl( ApiUrl.twUrl + this.articleItem.curl);
      this.link = ApiUrl.twUrl + this.articleItem.curl;
      console.log(this.articleItem);
    }, () => {

      console.log('出错了');
    });
  }
  collect() {
    if (this.userItem !== null) {
      this.api.getItem<AnswerVO>(ApiUrl.collectbtn,
        {'iuserid': this.userItem.iid, 'ifileid': this.articleid, 'itype': 1}).subscribe(response => {
        if (response === null) {
          console.log('没有数据返回');
          return;
        }
        this.item = response;
        if (this.item.success) {
          this.presentToast(this.item.msg);
          this.collectOrNot();
        }
      }, () => {

        console.log('出错了');
      });
    } else {
      this.router.navigate(['/login']);
    }

  }
  like() {
    if (this.userItem !== null) {
    this.api.getItem<AnswerVO>(ApiUrl.likebtn,
      {'iuserid': this.userItem.iid, 'ifileid': this.articleid, 'itype': 1}).subscribe(response => {
        if (response === null) {
          console.log('没有数据返回');
          return;
        }
        this.item = response;
        if (this.item.success) {
          this.presentToast(this.item.msg);
          this.likeOrnot();
        }
    }, () => {

      console.log('出错了');
    });
  } else {
    this.router.navigate(['/login']);
  }
  }
  collectOrNot() {
    this.api.getItem<AnswerVO>(ApiUrl.collectOrNot,
      {'iuserid': this.userItem.iid, 'ifileid': this.articleid, 'itype': 1}).subscribe(response => {
      if (response === null) {
        console.log('没有数据返回');
        return;
      }
      this.item = response;
      if (this.item.success) {
        this.collectColor = 'danger';
      } else {
        this.collectColor = '';
      }
    }, () => {

      console.log('出错了');
    });
  }
  likeOrnot() {
    this.api.getItem<AnswerVO>(ApiUrl.likeOrNot,
      {'iuserid': this.userItem.iid, 'ifileid': this.articleid, 'itype': 1}).subscribe(response => {
      if (response === null) {
        console.log('没有数据返回');
        return;
      }
      this.item = response;
      if (this.item.success) {
        this.likeColor = 'danger';
      } else {
        this.likeColor = '';
      }
    }, () => {

      console.log('出错了');
    });

  }
  addbrowse() {
    this.api.getItem<AnswerVO>(ApiUrl.addbrowse,
       {'iuserid': this.userItem.iid, 'ifileid': this.articleid, 'itype': 1}).subscribe(response => {
      if (response === null) {
        console.log('没有数据返回');
        return;
      }
      this.item = response;
    }, () => {

      console.log('出错了');
    });

  }
  async presentToast(msg) {
    const toast = await this.toastController.create({
      message: msg,
      duration: 2000
    });
    toast.present();
  }


  async presentActionSheet() {
    const actionSheet = await this.actionSheetController.create({
      header: '分享',
    buttons: [
        {
        text: '微信好友',
        handler: () => {
          this.wxShare(0);
        }
        },
        {
        text: '朋友圈',
        handler: () => {
          this.wxShare(1);
        }
        },
        {
        text: '取消',
        role: 'cancel',
        handler: () => {
            console.log('Cancel clicked');
        }
        }
    ]
    });
    actionSheet.present();
}


async wxShare(scene) {
  const loading = await this.loadingCtrl.create({ showBackdrop: false });
  loading.present();
  try {
      Wechat.share({
          message: {
              title: this.articleItem.ctitle,
              description: this.articleItem.cdesc,
              // thumb: 'this.image',
             // mediaTagName: 'TEST-TAG-001',
              messageExt: '',  // 这是第三方带的测试字段
              messageAction: '', // <action>dotalist</action>
              media: {
                  type: Wechat.Type.WEBPAGE,
                  webpageUrl: this.link
              }
          },
          scene: scene === 0 ? Wechat.Scene.SESSION : Wechat.Scene.Timeline  // share to Timeline
      }, function () {
          // alert("分享成功！");
      }, function (reason) {
          // alert("Failed: " + reason);
      });
  } catch (error) {
      console.log(error);
  } finally {
      loading.dismiss();
  }
}

}
